package com.gewu.bluetoothflow.ui

import android.app.TimePickerDialog
import android.app.TimePickerDialog.OnTimeSetListener
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TimePicker
import android.widget.Toast

import com.eciot.ble_demo_kotlin.ECBLE
import com.gewu.bluetoothflow.MyApp.Companion.ACTION_SEND_DATA
import com.gewu.bluetoothflow.MyApp.Companion.FILE_SELECT_CODE
import com.gewu.bluetoothflow.R
import com.gewu.bluetoothflow.bean.BleDeviceInfo
import com.gewu.bluetoothflow.bean.UpgradeInfo
import com.gewu.bluetoothflow.databinding.ActivityDevinfoBinding
import com.gewu.bluetoothflow.service.DataRefreshReceiver
import com.gewu.bluetoothflow.view.LoadingDialog
import com.gewu.bluetoothflow.view.TipDialog
import com.google.gson.Gson
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.io.File
import java.util.*


class DevInfoActivity :BaseActivity(), DataRefreshReceiver.Messages {
    val TAG: String = "DevInfoActivity"
    private lateinit var mbinding: ActivityDevinfoBinding;
    private  var currentDevice:BleDeviceInfo? = null

    private var startTime:String = ""
    private var endTime:String = ""
    var dataReceiver: DataRefreshReceiver? = null;
    var loadingDialog:LoadingDialog? = null
    var mTimer:Timer? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mbinding = ActivityDevinfoBinding.inflate(layoutInflater)
        setContentView(mbinding.root)

        val dev =  intent.getStringExtra("devInfo")
        currentDevice = Gson().fromJson(dev, BleDeviceInfo::class.java)


        mbinding.tvBack.setOnClickListener {
              finish()
        }

        dataReceiver = DataRefreshReceiver(this)
        val initentFilter = IntentFilter()
        initentFilter.addAction(ACTION_SEND_DATA)
        registerReceiver(dataReceiver,initentFilter,Context.RECEIVER_NOT_EXPORTED)
        mTimer = Timer()
    }


    override fun onStart() {
        super.onStart()
        initView()
        mbinding.selectFile.setOnClickListener {
            val intent = Intent(Intent.ACTION_GET_CONTENT)
            intent.setType("*/*") // 设置类型为所有文件
            startActivityForResult(intent, FILE_SELECT_CODE)
        }
    }
  //  val condition = mutableListOf<String>("twoWay","onlyIn","onlyOut")
   // var Direction:String = ""
   fun initView(){
       if (currentDevice!!.time.length != 14 ){
           return
       }
      //  val strTime = currentDevice!!.time.substring(0,4)+"-"+currentDevice!!.time.substring(4,6)+"-"+currentDevice!!.time.substring(6,8)+" "+currentDevice!!.time.substring(8,10)+":"+currentDevice!!.time.substring(10,12)+":"+currentDevice!!.time.substring(12,14)

        if (currentDevice!!.close.length != 4){
            return
        }
        if (currentDevice!!.open.length != 4){
            return
        }

       // val businTime = currentDevice!!.dataStartTime.substring(0,2)+":"+currentDevice!!.dataStartTime.substring(2,4)+"~"+currentDevice!!.dataEndTime.substring(0,2)+":"+currentDevice!!.dataEndTime.substring(2,4)

        mbinding.RecordPeriod.setText("${currentDevice!!.storCyc}")


       var direction = resources.getString(R.string.twoWay) //"双向"
       if (currentDevice!!.dir.equals("twoWay")){
           direction = resources.getString(R.string.twoWay)
       }else if (currentDevice!!.dir.equals("onlyIn")){
           direction = resources.getString(R.string.onlyIn)
       }else if (currentDevice!!.dir.equals("onlyOut")){
           direction = resources.getString(R.string.onlyOut)
       }else if (currentDevice!!.dir.equals("right")){
           direction = resources.getString(R.string.ltor)
       }else if (currentDevice!!.dir.equals("left")){
           direction = resources.getString(R.string.rtol)
       }
       mbinding.statisticalDirection.setText(direction)
       startTime = currentDevice!!.open
       endTime = currentDevice!!.close



       mbinding.devSn.setText(currentDevice!!.id)
       if (currentDevice!!.id.startsWith("150")){
           mbinding.mBattery.setText("${currentDevice!!.devBat}%")
           mbinding.llSecondaryBattery.visibility = View.GONE
       }else {
           if (mbinding.llSecondaryBattery.visibility == View.GONE){
               mbinding.llSecondaryBattery.visibility = View.VISIBLE
           }
           mbinding.mBattery.setText("${currentDevice!!.rxBat}%")
           mbinding.sBattery.setText("${currentDevice!!.txBat}%")
       }


       mbinding.sVersion.setText(currentDevice!!.ver)

       mbinding.RecordPeriod.setText("${currentDevice!!.storCyc} min")
       val start01 = currentDevice!!.open.substring(0,2) //.toInt()
       val start02 = currentDevice!!.open.substring(2,4) //.toInt()

       mbinding.startTime.setText("$start01:$start02")
       val end01 = currentDevice!!.close.substring(0,2) //.toInt()
       val end02 = currentDevice!!.close.substring(2,4) //.toInt()
       mbinding.endTime.setText("$end01:$end02")
/*
       mbinding.startTime.setOnClickListener {
           val timeDialog = TimePickerDialog(this,1,object :OnTimeSetListener{
               override fun onTimeSet(p0: TimePicker?, p1: Int, p2: Int) {
                   mbinding.startTime.setText( "$p1:$p2")
                   val start1 = if (p1 < 10) "0$p1" else "$p1"
                   val start2 = if (p2 < 10) "0$p2" else "$p2"
                   startTime = "$start1$start2"
               }
           },start01,start02,true)
           timeDialog.show()
       }

     /  mbinding.endTime.setOnClickListener {
           val timeDialog = TimePickerDialog(this,1,object :OnTimeSetListener{
               override fun onTimeSet(p0: TimePicker?, p1: Int, p2: Int) {
                   mbinding.endTime.setText( "$p1:$p2")
                   val start1 = if (p1 < 10) "0$p1" else "$p1"
                   val start2 = if (p2 < 10) "0$p2" else "$p2"
                   endTime = "$start1$start2"
               }
           },end01,end02,true)
           timeDialog.show()
       }

 */

      mbinding.restartDev.setOnClickListener {
           //  {"restart":"1"}   重启设备
          val mdialog = TipDialog(this, R.style.TransparentDialog,
              getString(R.string.confirm_restart),"")
          mdialog.show()
          mdialog.setSaveListener(object :TipDialog.EditDevClickListener {
              override fun onclickSave() {
                  val command =  "{\"restart\":\"1\"}"
                  Log.d(TAG,"重启设备 --> "+command)
                  Thread{
                      val state = ECBLE.writeBLECharacteristicValue(command, false)
                  }.start()
                  mdialog.dismiss()
                  showToast(resources.getString(R.string.success_send))
              }
          })
      }
   }

    override fun onStop() {
        super.onStop()
    }

    var mfilePath = ""  //固件路径
    override fun getMsg(str: String) {
        Log.d(TAG," --> "+str)
        if (str.contains("state")) {
            val bean = Gson().fromJson(str, UpgradeInfo::class.java)
            if (bean.state.equals("begin")) {
                if (mfilePath.length < 2) return
                val state = ECBLE.writeBLECharacteristicFile(File(mfilePath))
                mTimer!!.schedule(
                    object : TimerTask() {
                        override fun run() {
                            runOnUiThread {
                                if (loadingDialog != null) {
                                    loadingDialog!!.dismiss()
                                    showToast(resources.getString(R.string.fail_upgrade))
                                }
                            }
                        }
                    }, 300000
                )
            } else if (bean.state.equals("ok")) { //升级完成
                if (mTimer != null) {
                    mTimer!!.cancel()
                }
                if (loadingDialog != null) {
                    loadingDialog!!.dismiss()
                    showToast(resources.getString(R.string.success_upgrade))
                }
            }else if (bean.state.equals("error")){
                if (mTimer != null) {
                    mTimer!!.cancel()
                }
                if (loadingDialog != null) {
                    loadingDialog!!.dismiss()
                    showToast(resources.getString(R.string.fail_upgrade))
                }
            }
        }

        //{"info":"upgrade","state":"begin" } UpgradeInfo
        //{"info":"upgrade",”state“:"ok" }
        //{"info":"upgrade","len":541256 }    发送
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == FILE_SELECT_CODE && resultCode == RESULT_OK && data != null){
            val uri = data.data
            mfilePath = getFilePathFromUri(uri)
            //Log.d(TAG,"选择的文件路径 --> "+mfilePath)
            if (mfilePath.length < 2)return
            val mdialog = TipDialog(this, R.style.TransparentDialog,getString(R.string.ver_upgrade),mfilePath)
            mdialog.show()
            mdialog.setSaveListener(object :TipDialog.EditDevClickListener {
                override fun onclickSave() {
                    val file = File(mfilePath)
                    val len = file.length()
                    val command =  " {\"info\":\"upgrade\",\"len\":$len }"
                    Log.d(TAG,"文件大小 --> "+command)
                    mdialog.dismiss()
                    loadingDialog = LoadingDialog(this@DevInfoActivity, R.style.TransparentDialog)
                    loadingDialog!!.show()
                    Thread{
                        val state = ECBLE.writeBLECharacteristicValue(command, false)
                    }.start()
                }
            })
        }
    }

    fun getFilePathFromUri( uri: Uri?):String{
        var path = ""
        if ("content".equals(uri!!.scheme,true)){
            val projection = MediaStore.MediaColumns.DATA
            var cursor: Cursor? = null
            try {
                cursor = contentResolver.query(uri, arrayOf(projection),null,null,null)
                if (cursor != null && cursor.moveToFirst()) {
                    val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                    path = cursor.getString(columnIndex);
                }
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        } else if ("file".equals(uri.getScheme(),true)) {
            path = uri.getPath().toString();
        }
       return path
    }
































    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(dataReceiver)
    }




}